<template>
<!-- 订单列表 begin -->
<div class="main" id="main_order_manager">
	<Spin fix v-if="spinShow"></Spin>
	<div class="main-hd">
		<h2>订单列表</h2>
	</div>
	<div class="main-bd" id="order_manager">
		<div class="content-wrap">
			<div class="form-inline">
				<div>
					<Select v-model="investorId" class="w120 mr10 mb10" filterable>
						<Option
							v-for="(item, index) in investorList"
							:key="index"
							:value="item.investorId">{{ item.investorName }}</Option>
					</Select>
					<Select v-model="loanProductNo" class="w120 mr10 mb10">
						<Option
							v-for="(item, index) in loanProductNoList"
							:key="index"
							:value="item.loanProductNo"
						>{{ item.name }}</Option>
					</Select>
					<Input type="text" class="ivu-input-w200 mr10 mb10" v-model="orderNum" placeholder="订单编号" />
					<Input type="text" class="ivu-input-w200 mr10 mb10" v-model="name" placeholder="用户姓名" />
					<Input type="text" class="ivu-input-w200 mr10 mb10" v-model="cellphone" placeholder="账号" />
					<Select class="w120 mr10 mb10" v-model="loanDay">
						<Option :value="-1">借款期限</Option>
						<Option :value="7">7天</Option>
						<Option :value="14">14天</Option>
					</Select>
					<Select class="w120 mr10 mb10" v-model="loanState">
						<Option :value="-1">打款状态</Option>
						<Option :value="3">打款成功</Option>
						<Option :value="4">打款失败</Option>
						<Option :value="2">处理中</Option>
					</Select>
					<Select class="w120 mr10 mb10" v-model="repaymentState">
						<Option :value="-1">是否结清</Option>
						<Option :value="0">未还</Option>
						<Option :value="3">未结清</Option>
						<Option :value="1">结清</Option>
					</Select>
					<Select v-model="isExtend" class="w120 mr10 mb10" placeholder="是否展期">
						<Option :value="-1">是否展期</Option>
						<Option :value="0">未展期</Option>
						<Option :value="1">展期中</Option>
					</Select>
					<Select class="w120 mr10 mb10" v-model="isYuqi">
						<Option :value="-1">是否逾期</Option>
						<Option :value="0">未逾期</Option>
						<Option :value="1">已逾期</Option>
					</Select>
					<Select class="w120 mr10 mb10" v-model="platform">
						<Option value="all">全部平台</Option>
						<Option value="Android">Android</Option>
						<Option value="iOS">iOS</Option>
						<Option value="h5">h5</Option>
					</Select>

					<DatePicker type="daterange" :options="disDate" format="yyyy-MM-dd" @on-change="timeChange" placeholder="下单时间" class="mb10 mr10" style="width: 200px;vertical-align: middle;"></DatePicker>
					<DatePicker type="daterange" :options="disDate" format="yyyy-MM-dd" @on-change="passTimeChange" placeholder="打款时间" class="mb10 mr10" style="width: 200px;vertical-align: middle;"></DatePicker>
					<DatePicker type="daterange"  format="yyyy-MM-dd" @on-change="expireChange" placeholder="到期时间" class="mb10 mr10" style="width: 200px;vertical-align: middle;"></DatePicker>
				</div>
			</div>

			<!-- 订单列表 begin -->
			<div class="list" id="payment_bills_list">
				<table class="table table-hover table-condensed" id="payment_bills_list_table" border><thead><tr>
					<td>订单编号</td>
					<td>用户姓名</td>
					<td>账号</td>
					<td>所属客户</td>
					<td>借款金额</td>
					<td>借款期限</td>
					<td>综合费用</td>
					<td>打款状态</td>
					<td>打款时间</td>
					<td>是否结清</td>
					<td>是否展期</td>
					<td>下单时间</td>
					<td>应还时间</td>
					<td>贷款产品</td>
					<td>平台</td>
					<td>操作</td>
				</tr></thead>
				<tr v-for="item in orderList">
					<td>{{item.orderNum}}</td>
					<td>{{item.name}}</td>
					<td>{{item.cellphone}}</td>
					<td>{{ item.investorName }}</td>
					<td>{{item.primeCost}}</td>
					<td>{{item.loanDay}}天</td>
					<td>
						<Poptip trigger="hover" width="200">
							<div class="pop-table" slot="content">
								<p>利息：{{ item.interest }}</p>
								<p>违约金：{{ item.penal }}</p>
								<p>罚息：{{ item.interestOfDemurrage }}</p>
							</div>
							<p class="underline">{{ addCount(item.interest, item.penal, item.interestOfDemurrage) }}</p>
						</Poptip>
					</td>
					<td>{{loadStateArr[item.loanState]}}</td>
					<td>{{item.passTime}}</td>
					<td>{{ item.repaymentState | repayStateFormatter }}</td>
					<td>{{ item.isExtend | extendFormatter }}</td>
					<td>{{item.orderTime}}</td>
					<td>{{ item.latestPaymentDate }}</td>
					<td>{{ item.loanProductNo | productFormatter }}</td>
					<td>{{ item.platform }}</td>
					<td class="pt6 pb6">
						<Button size="small" class="btn-detail" type="primary" data-toggle="modal" data-target="#paymentDetailModal" @click="getOrderInfo(item.id)">详情</Button>
						<Button size="small" class="btn-setting" type="success" v-if="item.repaymentState != 1 && isShowSetting"  @click="handleSet(item.id, item.userId)">设置</Button>
					</td>
				</tr>
				</table>
			</div>
			<div style="float: right;margin-top:20px;text-align: right;">
				<Page
					:total="loan_list_size"
					:current.sync="page"
					:page-size-opts="[10, 20, 40, 80, 100]"
					show-total
					show-elevator
					show-sizer
					@on-change="pageChange"
					@on-page-size-change="handleSizeChange"
					style="margin: 15px 0;"></Page>
			</div>
			<!-- 订单列表 end -->

			<!-- 通知消息弹出层 begin -->
			<div class="modal fade" id="paymentDetailModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
				<div class="modal-dialog">
					<div class="modal-content">
						<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
							<h4 class="modal-title text-center">订单详情</h4>
						</div>
						<div class="modal-body">
							<div class="detailPayment" id="paymentDetail_list">
								<h2>订单信息</h2>
								<ul class="paymentUl">
									<li><em>订单编号：</em><span>{{detailPayment.orderNum}}</span></li>
									<li><em>下单时间：</em><span>{{detailPayment.orderTime}}</span></li>
									<li><em>用户姓名：</em><span>{{detailPayment.name}}</span></li>
									<li><em>银行卡账号：</em><span>{{detailPayment.bankNumber}}</span></li>
									<li><em>所属银行：</em><span>{{detailPayment.bankName}}</span></li>
									<li><em>手机号码：</em><span>{{detailPayment.cellphone}}</span></li>
									<li><em>借款金额：</em><span>{{detailPayment.primeCost}}</span></li>
									<li><em>借款期限：</em><span>{{detailPayment.loanDay}}天</span></li>
									<li><em>订单利息：</em><span>{{detailPayment.interest}}</span></li>
									<li><em>应还时间：</em><span>{{detailPayment.latestPaymentDate}}</span></li>
									<li><em>信审人员：</em><span>{{detailPayment.checkManagerName}}</span></li>
									<li><em>产品信息：</em><span>{{ detailPayment.loanProductNo | productFormatter }}</span></li>
								</ul>

								<h2>交易状态</h2>
								<ul class="paymentUl">
									<li><em>财务打款：</em><span>{{loadStateArr[detailPayment.loanState]}}</span></li>
									<li><em>打款时间：</em><span>{{detailPayment.passTime}}</span></li>
								</ul>

								<h2>账单信息</h2>
								<ul class="paymentUl">
									<li><em>应还金额：</em><span>{{ detailPayment.money }}</span></li>
									<li><em>已还金额：</em><span>{{ detailPayment.repaidMoney }}</span></li>
									<li><em>待还金额：</em><span>{{ detailPayment.shouldRepayMoney }}</span></li>
									<li><em>是否结清：</em><span>{{ detailPayment.repaymentState | repayStateFormatter }}</span></li>
									<li><em>结清时间：</em><span>{{ detailPayment.paymentDate }}</span></li>
									<li><em>是否逾期：</em><span>{{ detailPayment.isYuqi == 0 ? '未逾期' : '已逾期' }}</span></li>
									<li><em>逾期天数：</em>
										<span>{{ detailPayment.yuqiDay != 0 ? `${detailPayment.yuqiDay}天` : '-' }}</span>
									</li>
									<li><em>罚息：</em>
										<span>{{ detailPayment.interestOfDemurrage != 0 ? detailPayment.interestOfDemurrage : '-' }}</span>
									</li>
									<li><em>违约金：</em>
										<span>{{ detailPayment.penal != 0 ? detailPayment.penal : '-' }}</span>
									</li>
								</ul>

								<h2>还款记录</h2>
								<div class="paymentUl">
									<Table
										ref="rtable"
										border
										:data="rdata"
										:columns="rcolumns"
										:loading="rloading"
									>
									</Table>
								</div>

								<h2>展期记录</h2>
								<div class="paymentUl">
									<Table
										ref="extable"
										border
										:data="exdata"
										:columns="excolumns"
										:loading="exloading"
									></Table>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
			<!-- 通知消息弹出层 end -->

			<!-- 线下还款 begin-->
			<Modal
				v-model="repayModal"
				title="设置"
				:styles="{ top: '20px' }"
				:footer-hide="true"
				:mask-closable="false">
				<Tabs v-model="repayTab">
					<TabPane label="线下还款" name="repay">
						<Form ref="repayForm" :model="repayForm" :rules="repayRules" :label-width="90">
							<FormItem label="上传凭证" prop="uploadLists">
								<span slot="label" class="ivu-form-label">
									上传凭证
									<Poptip trigger="hover" placement="right">
										<Icon type="ios-help-circle" size="15"></Icon>
										<div slot="content" style="text-align:left;">
											<p>注意：1. 上传凭证后，可自动识别凭证相关信息；</p>
											<p>2. 只能上传jpg/png文件，且不超过1MB；最多只能上传1张图片。</p>
										</div>
									</Poptip>
								</span>
								<template v-if="uploadStatus == 'finished' && !uploadPending">
									<div class="upload-list" v-for="(item, index) in uploadList" :key="index">
										<img :src="item">
										<div class="upload-list-cover">
											<Icon type="ios-eye-outline" @click.native="handleView(index)"></Icon>
											<Icon type="ios-trash-outline" @click.native="handleRemove(index)"></Icon>
										</div>
									</div>
								</template>
								<template v-if="uploadStatus == 'start' && uploadPending">
									<div class="upload-list">
										<Progress status="success" :percent="uploadPercent" hide-info></Progress>
									</div>
								</template>
								<Upload
									ref="upload"
									:show-upload-list="false"
									:format="['jpg','jpeg','png']"
									:before-upload="handleBeforeUpload"
									accept="image/jpeg,image/png"
									type="drag"
									action=""
									style="display: inline-block;width:58px;">
									<div style="width: 58px;height:58px;line-height: 58px;">
										<Icon type="ios-camera" size="20"></Icon>
									</div>
								</Upload>

							</FormItem>
							<FormItem label="还款金额" prop="money">
								<Input type="text" placeholder="请输入还款金额（元）" v-model.trim="repayForm.money" number></Input>
							</FormItem>
							<FormItem label="还款时间" prop="repayDate">
								<DatePicker
									:options="repayFormOptions"
									style="width:100%"
									type="datetime"
									:value="repayForm.repayDate"
									placeholder="请选择还款时间"
									format="yyyy-MM-dd HH:mm:ss"
									@on-change="handleRepayDate"></DatePicker>
							</FormItem>
							<FormItem label="还款方式" prop="repayWay">
								<Select v-model="repayForm.repayWay" placeholder="请选择还款方式">
									<Option :value="item.code" v-for="(item, index) in repayWayList" :key="index">{{ item.name }}</Option>
								</Select>
							</FormItem>
							<FormItem label="交易单号" prop="orderNo">
								<Input type="text" placeholder="请输入交易单号" v-model.trim="repayForm.orderNo"></Input>
							</FormItem>
							<FormItem label="是否展期" prop="isExtend">
								<RadioGroup v-model="repayForm.isExtend">
									<Radio :label="0">否</Radio>
									<Radio :label="1">是</Radio>
								</RadioGroup>
							</FormItem>
							<FormItem label="展期天数" prop="extendDays" v-show="isRepayExtend">
								<Select v-model="repayForm.extendDays" placeholder="请选择展期天数" @on-change="handleRepaySelect">
									<Option :value="item" v-for="(item, index) in extendDaysList" :key="index">{{ item }}</Option>
								</Select>
								<div class="extend-infos">{{ repayExtendInfo }}</div>
							</FormItem>
							<FormItem label="是否结清" prop="payOff" v-show="!isRepayExtend">
								<RadioGroup v-model="repayForm.payOff">
									<Radio :label="0" :disabled="repayPayOff">否</Radio>
									<Radio :label="1">是</Radio>
								</RadioGroup>
							</FormItem>
							<FormItem label="是否锁定" prop="isLock" v-show="!isRepayExtend">
								<RadioGroup v-model="repayForm.isLock">
									<Radio :label="0">否</Radio>
									<Radio :label="1">是</Radio>
								</RadioGroup>
							</FormItem>
							<FormItem label="备注">
								<Input type="textarea" placeholder="请输入还款备注" required v-model.trim="remark"></Input>
							</FormItem>
							<FormItem>
								<Button type="primary" :loading="repaySpin" @click="handleRepaySubmit2()">
									<span v-if="!repaySpin">提交</span>
									<span v-else>提交中…</span>
								</Button>
								<Button @click="handleRepayReset('repayForm')" style="margin-left: 10px">重置</Button>
							</FormItem>
						</Form>
					</TabPane>
					<TabPane label="代扣" name="withhold">
						<Form ref="withholdForm" :model="withholdForm" :rules="withholdRules" :label-width="90">
							<FormItem label="是否展期" prop="isExtend">
								<RadioGroup v-model="withholdForm.isExtend">
									<Radio :label="0">否</Radio>
									<Radio :label="1">是</Radio>
								</RadioGroup>
							</FormItem>
							<FormItem label="展期天数" prop="extendDays" v-show="isWithholdExtend">
								<Select v-model="withholdForm.extendDays" placeholder="请选择展期天数" @on-change="handleWithholdSelect">
									<Option :value="item" v-for="(item, index) in extendDaysList" :key="index">{{ item }}</Option>
								</Select>
								<div class="extend-infos">{{ withholdExtendInfo }}</div>
							</FormItem>
							<FormItem label="还款金额" prop="money">
								<Input
									ref="withholdInput"
									type="text"
									placeholder="请输入还款金额（元）"
									v-model="withholdForm.money"
									number></Input>
							</FormItem>
							<FormItem label="代扣方式" prop="bankCardId">
								<Select v-model="withholdForm.bankCardId" placeholder="请选择代扣银行卡">
									<Option :value="item.id" v-for="(item, index) in bankList" :key="index">{{ item.bankName }} {{ item.accNo }}</Option>
								</Select>
							</FormItem>
							<FormItem label="原始展期费用" v-show="isWithholdExtend">
								<p>{{ originalExtendFee }}</p>
							</FormItem>
							<FormItem label="折扣" v-show="isWithholdExtend">
								<p>{{ detailPayment.discount }}</p>
							</FormItem>
							<FormItem label="原到期日" v-show="isWithholdExtend">
								<p>{{ timeFormat(detailPayment.oldDeadLine) }}</p>
							</FormItem>
							<FormItem label="新到期日" v-show="isWithholdExtend">
								<p>{{ timeFormat(newDeadLine) }}</p>
							</FormItem>
							<FormItem label="是否结清" prop="payOff" v-show="!isWithholdExtend">
								<RadioGroup v-model="withholdForm.payOff">
									<Radio :label="0" :disabled="withholdPayOff">否</Radio>
									<Radio :label="1">是</Radio>
								</RadioGroup>
							</FormItem>
							<FormItem label="是否锁定" prop="isLock" v-show="!isWithholdExtend">
								<RadioGroup v-model="withholdForm.isLock">
									<Radio :label="0">否</Radio>
									<Radio :label="1">是</Radio>
								</RadioGroup>
								</FormItem>
							<FormItem style="margin-top: 48px;">
								<Button type="primary" :loading="withholdSpin" @click="handleWithholdSubmit('withholdForm')">
									<span v-if="!withholdSpin">提交</span>
									<span v-else>提交中…</span>
								</Button>
								<Button @click="handleWithholdReset('withholdForm')" style="margin-left: 10px">重置</Button>
							</FormItem>
						</Form>
					</TabPane>
				</Tabs>
			</Modal>
			<!-- 线下还款 end-->

			<!-- 线下还款 预览上传图片 -->
			<Modal title="预览图片" v-model="previewVisible" class="proofimg-modal">
        <img :src="previewImage" v-if="previewImage" class="proofimg-pic">
				<p class="no-img" v-else>暂无图片</p>
    	</Modal>
			<!-- end -->

			<!-- 订单详情 预览凭证 -->
			<Modal
				title="查看凭证"
				class="proofimg-modal"
				v-model="previewProofImgs"
				@on-cancel="handleProofImgsCancel"
			>
				<template v-if="proofImgsArr.length > 0">
					<div v-for="(item, index) in proofImgsArr" :key="index">
						<p class="proofimg-labels" v-if="proofImgsArr.length > 1">
							<span class="proofimg-label">{{ index + 1 }}</span>
						</p>
						<img class="proofimg-pic" :src="item">
						<Divider v-if="proofImgsArr.length !== (index+1)" />
					</div>
				</template>
				<template v-else>
					<p class="no-img">暂无图片</p>
				</template>
    	</Modal>
			<!-- end -->
		</div>
	</div>
</div>
<!-- 订单列表 end -->
</template>

<script>
	import qs from 'qs';
	import lrz from 'lrz';
	import { mapGetters } from 'vuex';
	import { dateFormat } from '../static/tools';
	import mixin from '../libs/mixins.js';

	export default {
		mixins: [ mixin ],
		data() {
			const validateLimit = (rule, value, callback) => {
				const { shouldRepayMoney } = this.detailPayment;

        if (value > shouldRepayMoney) {
          callback(new Error('代扣还款金额不得超过待还金额'));
        } {
          callback();
        }
			};
			const validateLength = (rule, value, callback) => {
				const { orderNo, repayWay } = this.repayForm;
				let len = orderNo.length;
				// 微信位数限制28或31
				if (repayWay == 2) {
					if (len != 28 && len != 32) return callback(new Error('请核对交易单号或者商户单号'));
					callback();
				} else if (repayWay == 3) {
					if (len != 14) return callback(new Error('请核对交易单号或者商户单号'));
					callback();
				} else {
					callback();
				}
			};
			const validateDate = (rule, value, callback) => {
				const reg = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/;

				if (!reg.test(value)) return callback(new Error(`OCR识别时间【${value}】格式错误，请校对还款时间`));
				callback();
			}
			const validateRepayExtend = (rule, value, callback) => {
				if (this.isRepayExtend) {
					if (value <= 0) return callback(new Error('请选择展期天数'));
					callback();
				} else {
					callback();
				}
			}
			const validateWithholdExtend = (rule, value, callback) => {
				if (this.isWithholdExtend) {
					if (value <= 0) return callback(new Error('请选择展期天数'));
					callback();
				} else {
					callback();
				}
			}
			return {
				role: '',
				orderNum: '',
				name: '',
				cellphone: '',
				loanDay: -1,
				loanState: -1,
				repaymentState: -1,
				isYuqi: -1,
				isExtend: -1,
				platform: 'all',
				beginOrderTime: '',
				endOrderTime: '',
				beginPassTime: '',
				endPassTime: '',
				beginLatestPaymentDate: '',
				endLatestPaymentDate: '',
				loadStateArr: ['待处理','待确认','处理中','成功','失败'],
				orderList: [],
				detailPayment: {},
				loan_list_size: 1,
				loan_list_page: 1,
				loading: true,
				disDate: {
					disabledDate (date) {
						return date && date.valueOf() > Date.now();
					}
				},
				disDate1: {
					disabledDate (date) {
						return date && date.valueOf() > Date.now();
					}
				},
				repayModal: false,
				repayForm: {
					repayWay: '',
					money: '',
					uploadLists: [],
					repayDate: '',
					payOff: 0,
					isExtend: 0,
					extendDays: 0,
					isLock: 0,
					orderNo: ''
				},
				repayRules: {
					money: [
						{ required: true, type: 'number', message: '请输入还款金额', trigger: 'blur' }
					],
					uploadLists: [
						{ required: true, type: 'array', min:1, message: '请上传还款凭证', trigger: 'change' }
					],
					repayWay: [
						{ required: true, type: 'number', message: '请选择还款方式', trigger: 'change' }
					],
					repayDate: [
						{ required: true, type: 'string', message: '请选择还款时间', trigger: 'change' },
						{ validator: validateDate, trigger: 'change' }
					],
					payOff: [
						{ required: true, type: 'number', message: '请选择是否结清', trigger: 'change' }
					],
					isExtend: [
						{ required: true, type: 'number', message: '请选择是否展期', trigger: 'change' }
					],
					extendDays: [
						{ required: true, type: 'number', message: '请选择展期天数', trigger: 'change' },
						{ validator: validateRepayExtend, trigger: 'change' }
					],
					isLock: [
						{ required: true, type: 'number', message: '请选择是否锁定', trigger: 'change' }
					],
					orderNo: [
						{ required: true, message: '请输入交易单号', trigger: 'blur' },
						{ validator: validateLength, trigger: 'blur' }
					]
				},
				repayPayOff: false,
				remark: '',
				previewVisible: false,
				previewImage: '',
				uploadList: [],
				spinShow: false,
				repaySpin: false,
				withholdForm: {
					money: '',
					bankCardId: '',
					payOff: 0,
					isExtend: 0,
					extendDays: 0,
					isLock: 0
				},
				withholdRules: {
					money: [
						{ required: true, type: 'number', message: '请输入还款金额', trigger: 'blur' },
						{ validator: validateLimit, trigger: 'change' }
					],
					bankCardId: [
						{ required: true, type: 'number', message: '请选择代扣银行卡', trigger: 'change' }
					],
					payOff: [
						{ required: true, type: 'number', message: '请选择是否结清', trigger: 'change' }
					],
					isExtend: [
						{ required: true, type: 'number', message: '请选择是否展期', trigger: 'change' }
					],
					extendDays: [
						{ required: true, type: 'number', message: '请选择展期天数', trigger: 'change' },
						{ validator: validateWithholdExtend, trigger: 'change' }
					],
					isLock: [
						{ required: true, type: 'number', message: '请选择是否锁定', trigger: 'change' }
					]
				},
				withholdSpin: false,
				withholdPayOff: false,
				bankList: [],
				repayTab: 'repay',
				page: 1,
				pageSize: 10,
				investorId: '',
				investorList: [],
				loanProductNo: '',
				loanProductNoList: [],
				rloading: true,
				rdata: [],
				rcolumns: [
          {
            title: '还款时间',
            key: 'confirmTime',
            align: 'center'
          },
          {
            title: '还款金额',
            key: 'money',
            align: 'center'
          },
          {
            title: '还款类型',
            key: 'repayType',
						align: 'center',
						render: (h, params) => {
							const { repayType } = params.row;
							let text;

							if (repayType == 0) {
								text = '主动还款';
							} else if (repayType == 1) {
								text = '代扣';
							} else if (repayType == 2) {
								text = '线下还款';
							} else {
								text = '';
							}
              return h('span', text);
            }
					},
					{
            title: '还款方式',
            key: 'repayWay',
						align: 'center',
						render: (h, params) => {
							const { repayWay, repaymentBankName, repaymentBankNumber } = params.row;
							let text;

							if (repayWay == 0) {
								text = `银行卡【${repaymentBankName} ${repaymentBankNumber}】`;
							} else if (repayWay == 1) {
								text = '支付宝';
							} else if (repayWay == 2) {
								text = '微信';
							} else if (repayWay == 3) {
								text = '拉卡拉';
							} else {
								text = '';
							}

              return h('span', text);
            }
					},
					{
						title: '还款状态',
						key: 'state',
						align: 'center',
						render: (h, params) => {
							const { state, returnDesc } = params.row;
							let txtColor, txt;

							if (state == 0) {
								txtColor = '#19be6b';
								txt = '处理中';
							} else if (state == 1) {
								txtColor = '#515a6e';
								txt = '成功';
							} else {
								txtColor = '#ed4014';
								txt = `失败【${returnDesc}】`;
							}

							return h('span', {
								style: {
									color: txtColor
								}
							}, txt);
						}
					},
					{
						title: '还款备注',
						key: 'remark',
						align: 'center',
						render: (h, params) => {
							const { remark, isExtend } = params.row;
							return h('p', isExtend == 1 ? `【展期】${remark}` : remark)
						}
					},
					{
						title: '还款凭证',
						key: 'proofImgs',
						align: 'center',
						render: (h, params) => {
							const { proofImgs } = params.row;
							let isHide = proofImgs == '' || proofImgs == null || proofImgs == undefined;

							return h('div', {
                style: {
                  paddingTop: '5px',
                  paddingBottom: '5px'
                }
              }, [
								h('Button', {
									props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
										marginRight: '10px',
										display: isHide ? 'none' : 'inline-block'
                  },
                  on: {
                    click: () => {
                      this.handlePreviewRecordImage(proofImgs);
                    }
                  }
								}, '查看')
              ]);
						}
					}
				],
				exloading: true,
				exdata: [],
				excolumns: [
					{
						title: '展期时间',
            key: 'ctime',
						align: 'center',
						render: (h, params) => {
							const { ctime } = params.row;
							return h('span', dateFormat(ctime, 'year'));
						}
					},
					{
						title: '支付金额（元）',
            key: 'discountExtendFee',
            align: 'center'
					},
					{
						title: '原到期日',
            key: 'oldDeadLine',
						align: 'center',
						render: (h, params) => {
							const { oldDeadLine } = params.row;
							return h('span', dateFormat(oldDeadLine, 'year'));
						}
					},
					{
						title: '新到期日',
            key: 'newDeadLine',
						align: 'center',
						render: (h, params) => {
							const { newDeadLine } = params.row;
							return h('span', dateFormat(newDeadLine, 'year'));
						}
					}
				],
				repayFormOptions: {
					shortcuts: [{
						text: 'Today',
						value() {
							return new Date();
						},
						onClick: () => {

						}
					}]
				},
				uploadStatus: '',
				uploadPercent: 0,
				uploadPending: false,
				previewProofImgs: false, // 详情查看凭证弹窗
				proofImgsArr: [], // 详情查看凭证图片数组
				repayWayList: [], // 线下还款方式数组
				extendDaysList: [], // 展期天数数组
				repayExtendInfo: '', // 线下还款展期费用
				withholdExtendInfo: '', // 代扣展期费用
				originalExtendFee: '', // 展期原始费用
				newDeadLine: '' // 展期新到期日
			}
		},
		created () {
			this.role = Number(localStorage.getItem('type'));
		},
		mounted () {
			this.getLoanProductsList();
			this.getAllInverstorList();
		},
		computed: {
			...mapGetters([
				'type'
			]),
			isRepayExtend() {
				return !!this.repayForm.isExtend
			},
			isWithholdExtend() {
				return !!this.withholdForm.isExtend
			},
			isShowSetting() {
				return this.role == 0 || this.role == 1 || this.role == 4
			}
		},
		methods: {
			getCreditOrderList () {
				var param = {};
				var _self = this;
				param.orderNum = _self.orderNum;
				param.name = _self.name;
				param.cellphone = _self.cellphone;
				param.loanDay = _self.loanDay;
				param.loanState = _self.loanState;
				param.repaymentState = _self.repaymentState;
				param.isYuqi = _self.isYuqi;
				param.beginOrderTime = _self.beginOrderTime;
				param.endOrderTime = _self.endOrderTime;
				param.beginPassTime = _self.beginPassTime;
				param.endPassTime = _self.endPassTime;
				param.beginLatestPaymentDate = _self.beginLatestPaymentDate;
				param.endLatestPaymentDate = _self.endLatestPaymentDate;
				param.page = _self.page || 1;
				param.pageSize = _self.pageSize;
				param.investorId = _self.investorId;
				param.loanProductNo = _self.loanProductNo;
				param.isExtend = _self.isExtend;
				param.platform = _self.platform;

				this.$http.post(`/helsinki/admin/order/getCreditOrderListByCondition?t=${Date.now()}`,param)
				.then(function(res) {
					if (res.data.errcode == 0) {
						_self.orderList = res.data.data.list;
						_self.loan_list_size = res.data.data.size;
						_self.loan_list_page = param.page;
						_self.loading = false;
					}
				}, function(err) {
					console.log(err);
				});
			},
			getOrderInfo (id) {//获取订单详情
				this.spinShow = true;
				this.rloading = true;

				this.$http.post('/helsinki/admin/order/getOrderInfo', {
					orderId: id
				}).then(({ data: { errcode, info, data }}) => {
					if (errcode == 0) {
						this.detailPayment = data.orderInfo;
					}
					this.spinShow = false;
				}, err => {
					this.spinShow = false;
				});

				// 还款记录
				this.$http.post('/helsinki/admin/order/repay-record', {
					orderId: id
				}).then(({ data: { errcode, info, data } }) => {
					if (errcode == 0) {
						this.rdata = data;
					}
					this.rloading = false;
				}, error => {
					console.log(error);
				});

				// 展期记录
				this.$http.post('/helsinki/admin/order/extend-record', {
					orderId: id
				}).then(({ data: { errcode, info, data } }) => {
					if (errcode == 0) {
						this.exdata = data;
					}
					this.exloading = false;
				}, error => {
					console.log(error);
				})

			},
			handleRepayDate (e) {
				this.repayForm.repayDate = e;
			},
			timeChange (e) {
				if (typeof(e) == "undefined") {
					this.beginOrderTime = e[0];
				} else if(typeof(e) == "object") {
					this.beginOrderTime = e[0];
					this.endOrderTime = e[1];
					this.getCreditOrderList();
				}
			},
			passTimeChange (e) {
				if (typeof(e) == "undefined") {
					this.beginPassTime = e[0];
				} else if(typeof(e) == "object") {
					this.beginPassTime = e[0];
					this.endPassTime = e[1];
					this.getCreditOrderList();
				}
			},
			expireChange (e) {
				if(typeof(e) == "undefined") {
					this.beginLatestPaymentDate = e[0];
				}else if(typeof(e)=="object") {
					this.beginLatestPaymentDate = e[0];
					this.endLatestPaymentDate = e[1];
					this.getCreditOrderList();
				}
			},
			pageChange (e) {
				this.page = e;
				this.getCreditOrderList();
			},
			// 每页显示数量
			handleSizeChange (val) {
				this.pageSize = val;
				this.getCreditOrderList();
			},
			// 设置按钮
			async handleSet (id, userId) {
				this.spinShow = true;

				// 同时请求详情和获取银行卡列表
				const resultArr = await Promise.all(
					[
						this.$http.post('/helsinki/admin/order/getOrderInfo', {orderId: id}),
						this.$http.post('/helsinki/admin/adminUser/getUserBankCardList', { userId: userId }),
						this.$http.get('/helsinki/admin/order/repay-underline/repay-way'),
						this.$http.get('/helsinki/admin/order/extend-days')
					].map($http => {
						return $http.then(({ data: { errcode, info, data }}) => {
							if (errcode == 0) {
								return Promise.resolve(data);
							}
							return Promise.reject(info);
						})
						.catch(info => { console.log(info); });
					})
				)

				this.detailPayment = resultArr[0].orderInfo;
				this.bankList = resultArr[1].list;
				this.repayWayList = resultArr[2].repayWay;
				this.extendDaysList = resultArr[3];

				const {
					shouldRepayMoney,
					repaymentState,
					originalLatestPaymentDate,
					isExtend,
					isYuqi,
					originalExtendFee,
					oldDeadLine,
					newDeadLine } = this.detailPayment;

				this.withholdForm.isExtend = isExtend;
				this.withholdForm.money = shouldRepayMoney;
				this.originalExtendFee = originalExtendFee;
				this.newDeadLine = newDeadLine;

				this.repayModal = true;
				this.spinShow = false;
			},
			// 线下还款 选择展期天数
			handleRepaySelect(val) {
				const { repayForm } = this.$refs;
				if (!val) return repayForm.resetFields();
				const { extendSupportDays, orderExtendOptions } = this.detailPayment;
				let fee = '';
				orderExtendOptions.forEach(item => {
					if (item.extendDays === val) {
						fee = item.originalExtendFee;
					}
				});

				this.repayExtendInfo = `原始展期费用为${fee}元`;
			},
			// 线下还款 提交
			handleRepaySubmit (name) {
				this.$refs[name].validate((valid) => {
					if (valid) {
						this.repaySpin = true;
						this.$http.post('/helsinki/admin/order/repay-underline', qs.stringify({
							orderId: this.detailPayment.id,
							userId: this.detailPayment.userId,
							repayWay: this.repayForm.repayWay,
							paymentDate: this.repayForm.repayDate,
							money: this.repayForm.money,
							remark: this.remark,
							proofImgs: this.uploadList,
							isExtend: this.repayForm.isExtend,
							extendDays: this.isRepayExtend ? this.repayForm.extendDays : 0,
							payOff: this.isRepayExtend ? 0 : this.repayForm.payOff,
							isLock: this.isRepayExtend ? 0 : this.repayForm.isLock,
							orderNo: this.repayForm.orderNo
						})).then(({ data: { errcode, info, data } }) => {
							if (errcode == 0) {
                this.repayModal = false;
                debugger
								this.getCreditOrderList();
							}else{
                
								this.$Message.success(info);
							this.repaySpin = false;
              }
						}, error => {
							this.repaySpin = false;
						});
					}
				})
			},
			// 线下还款重置
			handleRepayReset (name) {
				this.uploadList = [];
				this.repayPayOff = false;
				this.$refs[name].resetFields();
			},
			// 预览图片
			handleView (index) {
				this.previewImage = this.uploadList[index];
				this.previewVisible = true;
			},
			// 删除图片
			handleRemove (index) {
				this.uploadList.splice(index, 1);
			},
			compress (image, width, height, ratio) {
				let canvas = document.createElement('canvas');
					canvas.width = width;
					canvas.height = height;
				let g = canvas.getContext('2d');
				g.drawImage(image, 0, 0, width, height);
				return canvas.toDataURL('image/jpeg', ratio);
			},
			handleBeforeUpload (file) {
				const reg = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
				const limit5 = file.size / 1024 / 1024 < 1;
				const check = this.uploadList.length < 1;

				if (!reg.test(file.type)) {
					this.$Message.error('只能上传jpg, jpeg, png格式的图片');
					return false;
				}
				if (!limit5) {
					this.$Message.error('上传的图片不能超过1MB');
					return false;
				}
				if (!check) {
					this.$Message.error('最多上传1张图片');
					return false;
				}

				this.uploadPercent = 0;
				this.uploadStatus = 'start';
				this.uploadPending = true;

				// 压缩图片
				lrz(file)
				.then(res => {
					const { base64 } = res;
					this.uploadPercent = 10;
					// BAIDU OCR
					this.$http.post('/helsinki/admin/order/repay-underline-ocr', {
						imgBase64: base64
					}).then(({ data: { errcode, info, data }}) => {
						if (errcode == 0) {
							this.uploadPercent = 100;
							this.repayForm.money = parseFloat(data.money);
							this.repayForm.repayDate = data.time;
							this.repayForm.orderNo = data.orderNo;
							this.repayForm.repayWay = data.payway;
							this.uploadList.push(base64);
							this.repayForm.uploadLists = this.uploadList;
							this.$Message.success('上传凭证成功');
							setTimeout(() => {
								this.uploadPending = false;
								this.uploadStatus = 'finished';
							}, 200);
						}
					}, error => {
						console.log(error);
					});
				})
				.catch(err => {
					this.$Message.error('压缩图片失败');
				})
				.always(res => {});

				return false;
			},
			// 代扣 选择展期天数
			handleWithholdSelect(val) {
				const { withholdForm } = this.$refs;
				if (!val) return withholdForm.resetFields();
				const { orderExtendOptions } = this.detailPayment;
				let extendObj = orderExtendOptions.filter(item => item.extendDays === val);
				this.originalExtendFee = extendObj[0].originalExtendFee;
				this.newDeadLine = extendObj[0].newDeadLine;
				this.withholdForm.money = extendObj[0].discountExtendFee;
			},
			// 代扣银行卡 提交
			handleWithholdSubmit (name) {
				this.$refs[name].validate((valid) => {
					if (valid) {
						this.withholdSpin = true;
						this.$http.post('/helsinki/admin/order/repay-withhold', {
							orderId: this.detailPayment.id,
							userId: this.detailPayment.userId,
							money: this.withholdForm.money,
							bankCardId: this.withholdForm.bankCardId,
							isExtend: this.withholdForm.isExtend,
							extendDays: this.isWithholdExtend ? this.withholdForm.extendDays : 0,
							payOff: this.isWithholdExtend ? 0 : this.withholdForm.payOff,
							isLock: this.isWithholdExtend ? 0 : this.withholdForm.isLock
						}).then(({ data: { errcode, info, data }}) => {
							if (errcode == 0) {
								this.$Message.success(info);
								this.repayModal = false;
								this.getCreditOrderList();
							}
							this.withholdSpin = false;
						}, error => {
							this.withholdSpin = false;
						});
					}
				})
			},
			// 代扣银行卡 重置
			handleWithholdReset (name) {
				this.withholdPayOff = false;
				this.$refs[name].resetFields();
			},
			handleTab (name) {
				// this.repayTab = name;
			},
			resetForm () {
				const { repayForm, withholdForm } = this.$refs;

				this.repayTab = 'repay';
				this.uploadList = [];
				this.detailPayment = {};
				this.repayExtendInfo = '';
				this.originalExtendFee = '';
				this.newDeadLine = '';
				this.repayPayOff = false;
				this.withholdPayOff = false;
				repayForm.resetFields();
				withholdForm.resetFields();
			},
			// 获取查询条件里面的下拉框【直投客户列表】
			getAllInverstorList () {
				this.$http.post('/helsinki/admin/investor/getAllInvestorList')
				.then(({ data: { data, errcode, info } }) => {
					if (errcode === 0) {
						this.investorList = data.list;
						if (this.investorList.length == 1) {
							this.investorId = this.investorList[0].investorId;
						} else {
							this.investorId = -1;
						}
					}
				}, error => {
					console.log(error);
				});
			},
			// 获取产品列表
			getLoanProductsList () {
				this.$http.post('/helsinki/admin/loan-products')
				.then(({ data: { data, errcode, info } }) => {
					if (errcode === 0) {
						this.loanProductNoList = data.data;
						if (data.data.length == 1) {
							this.loanProductNo = this.loanProductNoList[0].loanProductNo;
						} else {
							this.loanProductNo = 'all';
						}
					}
				}, error => {
					console.log(error);
				})
			},
			handlePreviewRecordImage (value) {
				this.proofImgsArr = value.split(';');
				this.previewProofImgs = true;
			},
			// 筛选条件
			handleFilterReset() {
				this.page = 1;
				this.getCreditOrderList();
			},
			timeFormat(stamp) {
				return dateFormat(stamp, 'year');
			},
			// 订单详情 预览弹窗 取消回调
			handleProofImgsCancel() {
				this.previewProofImgs = false;
				this.proofImgsArr = [];
			}
		},
		watch: {//检测v-model组件变化
			orderNum () {
				this.handleFilterReset();
			},
			name () {
				this.handleFilterReset();
			},
			cellphone () {
				this.handleFilterReset();
			},
			loanDay () {
				this.handleFilterReset();
			},
			loanState () {
				this.handleFilterReset();
			},
			repaymentState () {
				this.handleFilterReset();
			},
			isYuqi () {
				this.handleFilterReset();
			},
			isExtend () {
				this.handleFilterReset();
			},
			investorId (newVal, oldVal) {
				if (newVal !== '' && this.loanProductNo !== '') {
					this.handleFilterReset();
				}
			},
			repayModal (curVal) {
				if (!curVal) {
					this.resetForm();
				}
			},
			loanProductNo (newVal, oldVal) {
				if (newVal !== '' && this.investorId !== '') {
					this.handleFilterReset();
				}
			},
			platform() {
				this.handleFilterReset();
			},
			// 线下还款 监听还款金额
			'repayForm.money' (newVal, oldVal) {
				const { shouldRepayMoney, isYuqi } = this.detailPayment;

				if (newVal == '') return;

				// 未逾期，结清默认为是，不可修改
				if (isYuqi == 0) {
					this.repayPayOff = true;
					this.repayForm.payOff = 1;
					this.repayForm.isLock = 0;
					return;
				}

				// 已逾期，可修改
				if (newVal >= shouldRepayMoney) {
					this.repayPayOff = true;
					this.repayForm.payOff = 1;
					this.repayForm.isLock = 0;
				} else {
					this.repayPayOff = false;
					this.repayForm.payOff = 0;
					this.repayForm.isLock = 1;
				}
			},
			// 代扣 监听还款金额
			'withholdForm.money' (newVal, oldVal) {
				const { shouldRepayMoney, isYuqi } = this.detailPayment;

				if (newVal == '') return;
				// 未逾期，结清默认为是，不可修改
				if (isYuqi == 0) {
					this.withholdPayOff = true;
					this.withholdForm.payOff = 1;
					this.withholdForm.isLock = 0;
					return;
				}

				// 已逾期，可修改
				if (newVal >= shouldRepayMoney) {
					this.withholdPayOff = true;
					this.withholdForm.payOff = 1;
					this.withholdForm.isLock = 0;
				} else {
					this.withholdPayOff = false;
					this.withholdForm.payOff = 0;
					this.withholdForm.isLock = 1;
				}
			},
			// 代扣 监听展期
			'withholdForm.isExtend' (newVal, oldVal) {
				const {
					discountExtendFee,
					shouldRepayMoney
				} = this.detailPayment;

				// 代扣展期
				this.withholdForm.money = newVal ? discountExtendFee : shouldRepayMoney;
			}
		},
		filters: {
			repayTypeFormatter (value) {
				switch (value) {
					case 0:
						return '主动还款';
						break;
					case 1:
						return '代扣';
						break;
					case 2:
						return '线下还款';
						break;
					default:
						return '';
						break;
				}
			},
			repayWayFormatter (value) {
				switch (value) {
					case 0:
						return '银行卡';
						break;
					case 1:
						return '支付宝';
						break;
					case 2:
						return '微信';
						break;
					default:
						return '';
						break;
				}
			},
			repayStateFormatter (value) {
				switch (value) {
					case 0:
						return '未还';
						break;
					case 1:
						return '结清11';
						break;
					case 3:
						return '未结清';
						break;
					default:
						return '';
						break;
				}
			},
			dateFormatter (value) {
				return dateFormat(value, 'year');
			}
		}
	}
</script>

<style lang="scss">
	@import '../static/style.css';
	@import '../static/common.scss';

	.main {
		position: relative;
	}

	.ivu-form-label {
		display: inline-block;
		vertical-align: middle;
	}

	.ivu-icon {
		vertical-align: middle;
	}

	.ivu-form {
		.ivu-form-item-label {
			margin-bottom: 0;
		}
	}

	.ivu-form-item:last-child {
		margin-bottom: 0;
	}

	.underline {
		font-weight: bold;
		text-decoration: underline;
		cursor: pointer;
	}

	.upload-list {
		display: inline-block;
		width: 60px;
		height: 60px;
		text-align: center;
		line-height: 60px;
		border: 1px solid transparent;
		border-radius: 4px;
		overflow: hidden;
		background: #fff;
		position: relative;
		box-shadow: 0 1px 1px rgba(0,0,0,.2);
		margin-right: 4px;
		font-size: 0;
		img	{
			width: 100%;
			height: 100%;
			border-radius: 4px;
		}
	}

	.upload-list-cover {
		display: none;
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background: rgba(0,0,0,.6);
	}

	.upload-list:hover .upload-list-cover {
		display: block;
	}

	.upload-list-cover i {
		display: inline-block;
		color: #fff;
		font-size: 20px;
		cursor: pointer;
		margin: 0 4px;
		vertical-align: middle;
	}

	.proof-images {
		margin-top: 12px;
		img {
			max-height: 300px;
		}
	}

	.proofimg-modal {
		.no-img {
			text-align: center;
		}
		.proofimg-labels {
			margin-bottom: 5px;
			text-align: center;
		}
		.proofimg-label {
			display: inline-block;
			font-size: 14px;
			width: 24px;
			height: 24px;
			line-height: 24px;
			color: #fff;
			background: #2d8cf0;
			border-radius: 100%;
			text-align: center;
		}

		.proofimg-pic {
			display: block;
			width: 90%;
			margin: 0 auto;
		}
	}

	.extend-infos {
		margin-top: 2px;
		color: #ed4014;
		line-height: 16px;
	}
</style>
